# -*- coding: utf-8 -*-

from lib.probability import FreqDist
import char_inputs

def lev_distance(word1, word2):
    len_1=len(word1)+1
    len_2=len(word2)+1
    
    d = []
    for i in xrange(len_1):
        d.append([])
        for j in xrange(len_2):
            d[i].append(0)
            
    for i in xrange(len_1):
        d[i][0] = i
    
    for i in xrange(len_2):
        d[0][i] = i
    
    for i in xrange(1,len_1):
        for j in xrange(1,len_2):
            if word1[i-1]==word2[j-1]:
                cost=0
            else: 
                cost=1
                
            d[i][j] = min([
                           d[i-1][j] + 1, #deletion
                           d[i][j-1] + 1,     # insertion
                           d[i-1][j-1] + cost  # substitution
                           ])
    return d[-1][-1]



def printSeq(seq, printout=False):
    s=''
    for c in seq:
        s+=c
        s+='-'
    s=s[:-1]
    if printout: print s.encode('utf-8')
    return s

def flatten(x):
    """flatten(sequence) -> list

    Returns a single, flat list which contains all elements retrieved
    from the sequence and all recursively contained sub-sequences
    (iterables).

    Examples:
    >>> [1, 2, [3,4], (5,6)]
    [1, 2, [3, 4], (5, 6)]
    >>> flatten([[[1,2,3], (42,None)], [4,5], [6], 7, MyVector(8,9,10)])
    [1, 2, 3, 42, None, 4, 5, 6, 7, 8, 9, 10]"""

    result = []
    for el in x:
        #if isinstance(el, (list, tuple)):
        if hasattr(el, "__iter__"):
            result.extend(flatten(el))
        else:
            result.append(el)
    return result

def trimList(list):
    res = []
    for l in list:
        if not l is None and l != '':
            res.append(l)
    return res
    
    
def printSeq2(seq):
    """Pretty prints a list of tuples """
    s1=''
    s2=''
    for grkl,gr in seq:
        s1+=grkl
        s1+='-'
        s2+=gr
        s2+='-'        
    s1=s1[:-1]
    s2=s2[:-1]    
    print s1.encode('utf-8'),'/',s2.encode('utf-8')
    return (s1,s2)

import re
def read_words(filename, words=FreqDist()):
    file = open(filename, 'rb')
    contents = file.read() #.decode('utf-8')
    if contents.startswith('\xef\xbb\xbf'):
        contents = contents[3:] #strip BOM       
    contents = unicode(contents, 'utf-8')
    return _read_words(contents, words)

import model
def dict_from_file(filename,separator=' - ', data_suffix='.pickle_data'):
    try:
        d = model.read_model(filename+data_suffix)
        return d
    except:
        pass
    file = open(filename, 'rb')
    contents = file.read() #.decode('utf-8')
    if contents.startswith('\xef\xbb\xbf'):
        contents = contents[3:] #strip BOM       
    contents = unicode(contents, 'utf-8')
    d = {}
    for line in contents.splitlines():
        word, count = line.split(separator)
        d[word]=int(count)
    model.dump_model(d,filename+data_suffix)
    return d
        


def _read_words(contents, words):
    pattern = re.compile(r'(\w+)-(\d+)-(.+)', re.UNICODE)
    #print repr(contents)
    for line in contents.splitlines():
        #print repr(line)
        #print repr(line.split('-'))
        m = pattern.match(line)
        word = m.group(1)
        count = m.group(2)
        #(word, count, freq) =line.split('-')
        words.inc(word, int(count))
    print ' Total %d words, %d unique' % (words.N(), words.B())
    return words

def refineWords(words):
    "remove non greek words from a FreqDist"
    words2 = FreqDist()
    for w in words.samples():
        if isGreek(w):
            words2.inc(w,words.count(w))
    return words2

def simplifyWords(words): 
    "convert uppercase and accented words into simple, lowercase ones, from a FreqDist"
    words2 = FreqDist()
    for w in words.samples():
        w2 = w.lower().translate(char_inputs.simple_ch)
        words2.inc(w2,words.count(w))
    return words2

def isGreek(word):
    start1=0x0370
    end1=0x03ff
    start2=0x1f00
    end2=0x1fff
    greek_chars =  [c for c in word if ((ord(c)>=start1 and ord(c)<=end1)or(ord(c)>=start2 and ord(c)<=end2))]
    return len(greek_chars)==len(word)


def test_lev_distance():
    print lev_distance('kitten','sitting')
    print lev_distance('Sunday','Saturday')    
    print lev_distance('oresits','orestis')  
    print lev_distance(u'συμετεχοντες',u'συμμετεχοντες')      
    
if __name__ == '__main__':
    test_lev_distance()